package net.esj.basic.plugins.freemarker.templatemodel;

import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import net.esj.basic.utils.StringUtils;

import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

@Component("cutOfTemplateMethodModel")
@Scope("prototype")
public class CutOfTemplateMethodModel implements TemplateMethodModel {

	private String postfix = "...";
	
	@Override
	public Object exec(List arg0) throws TemplateModelException {
		String o = (String) arg0.get(0);
		Integer cut = 0;
		if(arg0.size()>1){
			try{
				cut = Integer.valueOf( arg0.get(1).toString());
			}catch(NumberFormatException e){
				throw new TemplateModelException(e);
			}
		}
		
		String append =postfix;
		if(arg0.size()>2){
			append =arg0.get(2).toString();
		}
		o = StringUtils.cutOf(o,append,cut);
		return o;
	}

	public void setPostfix(String postfix) {
		this.postfix = postfix;
	}

}
